package com.example.myapplication.services;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.myapplication.activity.MainActivity;
import com.example.myapplication.db.Data;
import com.example.myapplication.db.SQLiteManager;
import com.example.myapplication.onenet.MQTT;

import org.eclipse.paho.client.mqttv3.MqttException;

import java.text.SimpleDateFormat;

public class MQTTService extends Service {
    private MQTT mqtt;
    private String username = null;//MQTT客户端ID
    private String clientID = null;//MQTT客户端ID
    private String passWord = null;//MQTT客户端密钥
    private boolean saveFlag;//登录界面返回的是否保存密码的标志位
    public static Handler handler;
    private SQLiteManager dataHelper;//SQLite
    private SQLiteDatabase db;//SQLite
    Cursor cursor1;
    private SimpleDateFormat df = new SimpleDateFormat(Data.DATE_FORMAT_Y);//设置日期格式
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        dataHelper = new SQLiteManager(this);
        db = dataHelper.getReadableDatabase();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Bundle bundle = intent.getExtras();
        username = bundle.getString(Data.COLUMN_Username);
        clientID = bundle.getString(Data.COLUMN_ClientID);
        passWord = bundle.getString(Data.COLUMN_Password);
        saveFlag = bundle.getBoolean(Data.COLUMN_SaveFlag);
        mqtt = new MQTT(this, username, clientID, passWord, saveFlag);


//        handler = new Handler(){
//            @Override
//            public void handleMessage(@NonNull Message msg) {
//                super.handleMessage(msg);
//                Message message = new Message();
//                message.what = msg.what;
//                message.obj = msg.obj;
//                message.setData(msg.getData());
//                MainActivity.handler.sendMessage(message);
//            }
//        };
        handler = new Handler() {

            @SuppressLint({"SetTextIl8n", "HandlerLeak", "Range"})

            public void handleMessage(Message msg) {

                super.handleMessage(msg);

                switch (msg.what) {

                    case 1: //开机校验更新回传
                        Toast.makeText(MQTTService.this, "Receive MQTT", Toast.LENGTH_SHORT).show();

                        break;

                    case 2: //反馈回转

                        break;

                    case 3: //MQTT收到消息

                        String message = msg.getData().getString(Data.MQTTReceiveMessage);
                        String topic = (String) msg.obj;
                        if(topic.indexOf(Data.TopicLoongSonSync) != -1){
                            /**
                             * 发送到MainActivity用于布局的更新
                             * */
                            Message info = new Message();
                            info.what = msg.what;
                            info.obj = msg.obj;
                            info.setData(msg.getData());
                            MainActivity.handler.sendMessage(info);
                            try {
                                String[] str = message.split("_");
                                mqtt.mqttSubscribe(str[0] + "/" + Data.TopicSyncNodeStatus, 1);
                                mqtt.mqttSubscribe(str[0] + "/" + Data.TopicNodeLocalSync, 0);
                                mqtt.mqttSubscribe(str[0] + "/" + Data.TopicNodeSync, 1);
                                //发出同步当前龙芯终端下节点信息的请求
                                mqtt.publishMessage(str[0] + Data.TopicNodeSyncRequest, "1");
                                mqtt.publishMessage(str[0] + Data.TopicNodeLocalSyncRequest, str[0] + "_1");
                            } catch (MqttException e) {
                                e.printStackTrace();
                            }
                        }else if (topic.indexOf(Data.TopicNodeSync) != -1) {
                            if (!message.equals("1")) {
                                try {
                                    String[] str = message.split("~");//Tips:龙芯id号~节点id号~传感器数量~传感器类型_传感器类型
                                    db = dataHelper.getReadableDatabase();
                                    cursor1 = db.query(Data.NodeArray_Table, null, Data.COLUMN_Gateway +"=? and " +
                                            Data.COLUMN_NodeName+"=?", new String[]{str[0], str[1]}, null, null, null);
                                    ContentValues values = new ContentValues();
                                    values.put(Data.COLUMN_Gateway, str[0]);
                                    values.put(Data.COLUMN_NodeName, str[1]);
                                    values.put(Data.COLUMN_NodeState, 1);//标记为在线
                                    values.put(Data.COLUMN_SensorNum, str[2]);
                                    values.put(Data.COLUMN_SensorTypeArray, str[3]);
                                    if(cursor1.getCount() == 0){
                                        db.insert(Data.NodeArray_Table, null, values);
                                    }else {
                                        db.update(Data.NodeArray_Table, values, Data.COLUMN_Gateway +"=? and " +
                                                Data.COLUMN_NodeName+"=?", new String[]{str[0], str[1]});
                                    }
                                    cursor1.close();
                                    db.close();
                                    mqtt.mqttSubscribe(str[0] + "/" + str[1] + "/#", 2);//Tips:loongson0/01/#
                                } catch (MqttException e) {
                                    e.printStackTrace();
                                }
                            } else {
//                                try {
//                                    String[] str = message.split("~");//Tips:龙芯id号~节点id号~传感器数量~传感器类型_传感器类型
//                                    mqtt.mqttSubscribe(str[0] + "/" + Data.TopicSyncNodeStatus, 2);
//                                } catch (MqttException e) {
//                                    e.printStackTrace();
//                                }
                            }
                        } else if (topic.indexOf(Data.TopicNodeLocalSync) != -1) { //收到节点位置信息
                            /**
                             * //Tips:GatewayID~NodeName~Area~Axis
                             * */
                            try {
                                String[] str = message.split("~");
                                db = dataHelper.getReadableDatabase();
                                cursor1 = db.query(Data.NodeLocal_Table, null, Data.COLUMN_Gateway +"=? and " +
                                        Data.COLUMN_NodeName+"=?", new String[]{str[0], str[1]}, null, null, null);

                                ContentValues values = new ContentValues();
                                values.put(Data.COLUMN_Gateway, str[0]);
                                values.put(Data.COLUMN_NodeName, str[1]);
                                values.put(Data.COLUMN_Area, str[2]);
                                values.put(Data.COLUMN_LocalInfo, str[3]);
                                if(cursor1.getCount() == 0){
                                    db.insert(Data.NodeLocal_Table, null, values);
                                }else {
                                    db.update(Data.NodeLocal_Table, values, Data.COLUMN_Gateway +"=? and " +
                                            Data.COLUMN_NodeName+"=?", new String[]{str[0], str[1]});
                                }
                                cursor1.close();
                                db.close();
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }else if (topic.indexOf(Data.TopicLoongSonWill) != -1) { //收到龙芯遗嘱
                            try {
                                String[] str = message.split("_");  //Tips:loongson0_UPLine
                                if (str[1].equals("DownLine")) {
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                        } else if (topic.indexOf(Data.TopicSyncNodeStatus) != -1) {
                            //更改相应的节点状态到数据库
                            try {
                                db = dataHelper.getReadableDatabase();
                                String[] str = message.split("_");
                                ContentValues values = new ContentValues();
                                values.put(Data.COLUMN_NodeState, str[2]);
                                db.update(Data.NodeArray_Table, values, Data.COLUMN_Gateway +"=? and " +
                                        Data.COLUMN_NodeName+"=?", new String[]{str[0], str[1]});
                                db.close();
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                        } else if(topic.indexOf(Data.TopicData) != -1){
                            /**
                             * //Tips:龙芯ID_id号_时间_电池电量_传感器数量_传感器类型_传感器数据_传感器类型_传感器数据
                             * */
                            try {
                                //System.out.println(message);
                                db = dataHelper.getReadableDatabase();
                                String[] str = message.split("_");
                                ContentValues values = new ContentValues();
                                values.put(Data.COLUMN_Gateway, str[0]);
                                values.put(Data.COLUMN_NodeName, str[1]);
                                values.put(Data.COLUMN_Time, df.format(System.currentTimeMillis()).toString());
                                values.put(Data.COLUMN_BatteryLevel, str[2]);
                                values.put(Data.COLUMN_SensorNum, str[3]);
                                for (int i = 0; i < Integer.valueOf(str[3]).intValue(); i++) {
                                    values.put(Data.COLUMN[6 + i * 2], str[4 + i * 2]);
                                    values.put(Data.COLUMN[7 + i * 2], str[5 + i * 2]);
                                }
                                db.insert(Data.SensorData_Table, null, values);
                                db.close();
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                        }
//                        System.out.println(message);
                        break;

                    case 30: //连接失败

                        Toast.makeText(MQTTService.this, "连接失败", Toast.LENGTH_SHORT).show();

                        break;

                    case 31: //连接成功

                        Toast.makeText(MQTTService.this, "连接成功", Toast.LENGTH_SHORT).show();

                        try {
                            /**
                             * 订阅同步龙芯节点信息主题和遗嘱主题
                             * */
                            mqtt.mqttSubscribe(Data.TopicLoongSonSync, 2);
                            mqtt.mqttSubscribe(Data.TopicLoongSonWill, 2);
                        } catch (MqttException e) {

                            e.printStackTrace();

                        }
                        /**
                         * 发出同步请求
                         * */
                        mqtt.publishMessage(Data.TopicLoongSonSyncRequest, "1");

                        break;
                    case 32:

                        mqtt.publishMessage((String) msg.obj, msg.getData().getByteArray(Data.MQTTPublishMessage));
                        break;
                    case 33:

                        mqtt.publishMessage((String) msg.obj, msg.getData().getString(Data.MQTTPublishMessage));
                        break;
                    default:

                        break;
                }
            }
        };
        return START_NOT_STICKY;
    }
}
